package com.pro.common.service.sitecontent.service;

import com.pro.common.api.CommonConst;
import com.pro.common.api.enums.init.EnumCurrency;
import com.pro.common.api.sitecontent.model.dto.CurrencyExchangeRateKey;
import com.pro.common.api.sitecontent.model.response.CurrencyExchangeRateContainer;
import com.pro.common.service.sitecontent.dao.CurrencyExchangeRateDao;
import com.pro.common.api.sitecontent.model.db.CurrencyExchangeRate;
import com.pro.framework.api.util.CollUtils;
import com.pro.framework.mybatisplus.BaseService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 国家 服务实现类
 */
@Service
public class CurrencyExchangeRateService extends BaseService<CurrencyExchangeRateDao, CurrencyExchangeRate> {

    public List<CurrencyExchangeRate> getActiveList(CurrencyExchangeRate entity) {
        return this.lambdaQuery().setEntity(entity)
                .eq(CurrencyExchangeRate::getEnabled, CommonConst.Num.YES)
                .orderByAsc(CurrencyExchangeRate::getSort)
                .list();
    }

    public LinkedHashMap<EnumCurrency, Map<EnumCurrency, BigDecimal>> getRateMapMap() {
        List<CurrencyExchangeRate> list = this.list();
        Map<CurrencyExchangeRateKey, CurrencyExchangeRate> map = CollUtils.listToMap(list, CurrencyExchangeRate::toKey);
        list.forEach(e -> {
            CurrencyExchangeRate revert = new CurrencyExchangeRate();
            revert.setFromCurrency(e.getToCurrency());
            revert.setToCurrency(e.getFromCurrency());
            CurrencyExchangeRateKey key = revert.toKey();
            CurrencyExchangeRate currencyExchangeRate = map.get(key);
            if (currencyExchangeRate == null) {
                revert.setRate(BigDecimal.ONE.divide(e.getRate(), 6, RoundingMode.HALF_UP));
                // 如果反向汇率不存在,就用正向取反返回
                map.put(key, revert);
            }
        });
        Collection<CurrencyExchangeRate> values = map.values();
        return CollUtils.groupBy(values, CurrencyExchangeRate::getFromCurrency, subList -> CollUtils.listToMap(subList, CurrencyExchangeRate::getToCurrency, CurrencyExchangeRate::getRate));
    }
}
